package api

import (
	"common/biz"
	"common/config"
	"common/logs"
	"common/resp"
	"common/rpc"
	"context"
	"core/xyError"
	"gate/jwts"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"time"
	"user/pb"
)

type UserHandler struct {
}

func NewUserHandler() *UserHandler {
	return &UserHandler{}
}

// Register 注册
func (u *UserHandler) Register(ctx *gin.Context) {
	var param pb.RegisterParams
	// 1. 接收参数
	if err := ctx.ShouldBindJSON(&param); err != nil {
		resp.Fail(ctx, biz.RequestDataError)
		return
	}
	// 2. gRPC 调用用户服务
	response, err := rpc.UserClient.Register(context.TODO(), &param)
	if err != nil {
		resp.Fail(ctx, xyError.ToError(err))
		return
	}
	connector := config.Conf.Services["connector"]
	// 3. 生成 token
	jwtConf := config.Conf.Jwt
	claims := jwts.CustomClaims{
		Uid: response.Uid,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(jwtConf.Exp) * 24 * time.Hour)),
		},
	}
	token, err := jwts.GenToken(&claims, jwtConf.Secret)
	if err != nil {
		logs.Error("生成 jwt 失败！error：%v", err)
		resp.Fail(ctx, biz.Fail)
		return
	}
	result := map[string]any{
		"token": token,
		"serverInfo": map[string]any{
			"host": connector.ClientHost,
			"port": connector.ClientPort,
		},
	}
	resp.Success(ctx, result)
}
